package com.itshare.video.common.config.resolver;

import com.alibaba.fastjson.JSONObject;
import com.itshare.video.common.annontation.WebData;
import com.itshare.video.common.aop.AopPropertyUtils;
import com.itshare.video.common.aop.AopUtils;
import com.itshare.video.common.aop.xss.annontation.CleanXSS;
import com.itshare.video.common.util.ValidateUtils;
import com.itshare.video.common.util.XssUtil;
import com.itshare.video.common.web.WebUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

/**
 * 获取 url + formdata + json
 * @Author lyr
 * @create 2020/11/10 23:42
 */
@Component
@Lazy
public class WebDataResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(WebData.class);
    }


    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        Class<?> clazz = parameter.getParameterType();
        if (!AopPropertyUtils.isJavaApi(clazz)) {
            //自定义对象
            JSONObject jsonResult = WebUtil.getJson(request);
            if (jsonResult==null) {
                jsonResult = new JSONObject();
            }
            for (Field field: clazz.getDeclaredFields()) {
                String key =field.getName();
                Object paramVal = request.getParameter(key);
                if (paramVal!=null) {
                    jsonResult.put(key,paramVal);
                }
            }
            Object res = jsonResult.toJavaObject(clazz);
            if (parameter.hasParameterAnnotation(CleanXSS.class) || clazz.isAnnotationPresent(CleanXSS.class)) {
                //清除XSS
                XssUtil.removeXSSWithBean(res);
            }
            validateUtils.doValidate(parameter,res);
            return res;
        }
        return null;
    }

    @Resource
    private ValidateUtils validateUtils;
}
